package com.zzc.util;

import com.zzc.domain.Admin;
import com.zzc.service.impl.AdminServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    AdminServiceImp adminServiceImp;

    //在请求处理的方法之前执行，放回true就通过，放回false就拦截。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                String email = "";
                String password = "";
                for (Cookie cookie : cookies) {
                    if ("email".equals(cookie.getName())) {
                        email = cookie.getValue();
                    } else if ("password".equals(cookie.getName())) {
                        password = cookie.getValue();
                    }
                }
                System.out.println("cookies");
                if(!email.equals("")&&!password.equals("")){
                    Admin admin = adminServiceImp.loginAuthentication(email);
                    if (admin==null){
                        response.sendRedirect("/login");
                        return false;
                    }else if (admin.getPwd().equals(password)){
                        request.getSession().setAttribute("username", "Zzc");
                        return true;
                    }else {
                        response.sendRedirect("/login");
                        return false;
                    }
                }else {
                    response.sendRedirect("/login");
                    return false;
                }
            }else {
                response.sendRedirect("/login");
                return false;
            }

        } else if ("lock".equals(username)){
            response.sendRedirect("/lock");
            return false;
        } else {
            return true;
        }
    }

    //在请求处理方法执行之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //该方法将在整个请求结束之后，也就是在 DispatcherServlet 渲染了对应的视图之后执行。此方法主要用来进行资源清理。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
